package com.jzg.common.cron4j;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.cron4j.ITask;
import com.jzg.common.model.sys.SysOrg;
import com.jzg.common.model.sys.SysRole;
import com.jzg.common.model.sys.SysUser;
import com.jzg.common.model.sys.SysUserOrg;
import com.jzg.common.model.sys.SysUserRole;
import com.jzg.common.util.PinYinUtil;
import com.jzg.common.util.UuidUtil;

public class PLAGTask implements ITask{
	
	protected final Log log = Log.getLog(getClass());
	private boolean isEnd = true;
//	private static String warnPath = PropKit.use("app-config-dev.txt").get("warnPath");
	ExecutorService executor = Executors.newFixedThreadPool(1);

	@Override
	public void run() {
		if (!isEnd)return;
		isEnd = false;
	    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
	        @Override
	        public Integer get() {
	        	try {
	        		List<Record> records=Db.use("plga").find("select * from Manage where NState <> '-1' ");
		        	List<Record> roles=Db.use("plga").find("select * from ManaRole ");
		        	List<Record> orgs=Db.use("plga").find("select * from PoliceOffice ");
		        	SysRole role;
		        	StringBuffer rolesb = new StringBuffer();
		        	for(Record record:roles) {
		        		role = SysRole.dao.findById(record.getStr("NId"));
		        		if(role==null) {
		        			role =new SysRole();
		        			role.setID(record.getStr("NId"));
		        			role.setNAME(record.getStr("SName"));
		        			role.setCODE(PinYinUtil.getPinyin(record.getStr("SName")));
		        			role.setREMARK(record.getStr("SDesc"));
		        			role.save();
		        		}else {
		        			role.setNAME(record.getStr("SName"));
		        			role.setCODE(PinYinUtil.getPinyin(record.getStr("SName")));
		        			role.setREMARK(record.getStr("SDesc"));
		        			role.update();
		        		}
		        		rolesb.append("'").append(record.getStr("NId")).append("'").append(",");
		        	}
		        	if(!StrKit.isBlank(rolesb.toString())) {
						Db.delete("delete from "+SysRole.TABLE_NAME+" where ID not in ("+(rolesb.substring(0,rolesb.length()-1))+") ");
					}
		        	
		        	log.info("==================开始同步用户====================");
		        	SysUser user;
		        	StringBuffer usersb = new StringBuffer();
		        	for(Record record:records) {
		        		user = SysUser.dao.findById(record.getStr("NId"));
		        		if(user==null) {
		        			user=new SysUser();
		        			user.setID(record.getStr("NId"));
		        			user.setNAME(record.getStr("SName"));
		        			user.setUSERNAME(record.getStr("SUserName"));
		        			user.setPASSWORD(record.getStr("SPassword"));
		        			user.setORGID(record.getStr("NOfficeId"));
		        			user.setCREATETIME(new Date(System.currentTimeMillis()));
//		        			if(!StrKit.isBlank(record.getStr("SPath"))) {
//		        				String base64Str = YTUtil.imgBase64(warnPath+record.getStr("SPath"));
//		        				user.setPHOTO(base64Str);
//		        				user.setPHOTOIMG(YTUtil.getImgBaseStr(warnPath+record.getStr("SPath"),base64Str));
//		        			}
		        			user.setSRC("1");
		        			user.save();
		        		}else {
		        			user.setNAME(record.getStr("SName"));
		        			user.setUSERNAME(record.getStr("SUserName"));
		        			user.setPASSWORD(record.getStr("SPassword"));
		        			user.setORGID(record.getStr("NOfficeId"));
		        			user.setCREATETIME(new Date(System.currentTimeMillis()));
//		        			if(!StrKit.isBlank(record.getStr("SPath"))) {
//		        				String base64Str = YTUtil.imgBase64(warnPath+record.getStr("SPath"));
//		        				user.setPHOTO(base64Str);
//		        				user.setPHOTOIMG(YTUtil.getImgBaseStr(warnPath+record.getStr("SPath"),base64Str));
//		        			}
		        			user.setSRC("1");
		        			user.update();
		        		}
		        		
		        		String NGroup=record.getStr("NGroup");
		        		if(!StrKit.isBlank(NGroup)) {
		        			String[] NGroups=NGroup.split("\\|");
		        			StringBuffer sysUserRoleSb = new StringBuffer();
		        			for(String group:NGroups) {
		        				SysUserRole userRole=SysUserRole.dao.findFirst("select * from "+SysUserRole.TABLE_NAME+" where ROLEID=? and USERID=? ",group,record.getStr("NId"));
		        				if(userRole==null) {
		        					userRole=new SysUserRole();
		        					userRole.setROLEID(group);
		        					userRole.setUSERID(record.getStr("NId"));
		        					userRole.setID(UuidUtil.getUUID());
		        					userRole.save();
		        				}
		        				sysUserRoleSb.append("'").append(group).append("'").append(",");
		        			}
		        			if(!StrKit.isBlank(sysUserRoleSb.toString())) {
	    						Db.delete("delete from "+SysUserRole.TABLE_NAME+" where ROLEID not in ("+(sysUserRoleSb.substring(0,sysUserRoleSb.length()-1))+") AND USERID=? ",record.getStr("NId"));
	    					}
		        		}
		        		String SMayGroups=record.getStr("SMayGroups");
		        		if(!StrKit.isBlank(SMayGroups)) {
		        			String[] orgGroups=SMayGroups.split("\\|");
		        			StringBuffer sysUserOrgSb = new StringBuffer();
		        			for(String group:orgGroups) {
		        				SysUserOrg userOrg=SysUserOrg.dao.findFirst("select * from "+SysUserOrg.TABLE_NAME+" where ORGID=? and USERID=? ",group,record.getStr("NId"));
		        				if(userOrg==null) {
		        					userOrg=new SysUserOrg();
		        					userOrg.setORGID(group);
		        					userOrg.setUSERID(record.getStr("NId"));
		        					userOrg.setID(UuidUtil.getUUID());
		        					userOrg.save();
		        				}
		        				sysUserOrgSb.append("'").append(group).append("'").append(",");
		        			}
		        			if(!StrKit.isBlank(sysUserOrgSb.toString())) {
	    						Db.delete("delete from "+SysUserOrg.TABLE_NAME+" where ORGID not in ("+(sysUserOrgSb.substring(0,sysUserOrgSb.length()-1))+") AND USERID=? ",record.getStr("NId"));
	    					}
		        		}
		        		usersb.append("'").append(record.getStr("NId")).append("'").append(",");
		        	}
		        	if(!StrKit.isBlank(usersb.toString())) {
						Db.delete("delete from "+SysUser.TABLE_NAME+" where USERNAME <> 'system' AND ID not in ("+(usersb.substring(0,usersb.length()-1))+") AND ID NOT IN (SELECT USERID FROM BIZ_CAB_STORE_USER GROUP BY USERID) ");
					}
		        	
		        	
		        	SysOrg org;
		        	SysOrg root = SysOrg.dao.findFirst("select * from "+SysOrg.TABLE_NAME+" where NAME='盘龙分局' ");
		        	StringBuffer orgsb = new StringBuffer();
		        	for(Record record:orgs) {
		        		org = SysOrg.dao.findById(record.getStr("NId"));
		        		if(org==null) {
		        			org =new SysOrg();
		        			org.setID(record.getStr("NId"));
		        			org.setNAME(record.getStr("SName"));
		        			org.setCODE(record.getStr("bmdm"));
		        			if(root==null) {
		        				org.setPARENTID("root");
		        			}else {
		        				org.setPARENTID(root.getID());
		        			}
		        			org.save();
		        		}else {
		        			if(root!=null) {
		        				org.setPARENTID(root.getID());
		        			}
		        			org.setNAME(record.getStr("SName"));
		        			org.setCODE(record.getStr("bmdm"));
		        			org.update();
		        		}
		        		orgsb.append("'").append(record.getStr("NId")).append("'").append(",");
		        	}
		        	if(!StrKit.isBlank(orgsb.toString())) {
						Db.delete("delete from "+SysOrg.TABLE_NAME+" where ID not in ("+(orgsb.substring(0,orgsb.length()-1))+") AND ID NOT IN (SELECT ORGID FROM BIZ_CAB) ");
					}
				} catch (Exception e) {
					log.info(e.getMessage());
				}
	        	isEnd = true;
	            return 1;
	        }
	    }, executor);
	    future.thenAccept(e -> {
	    	isEnd = true;
	    });
	}

	@Override
	public void stop() {
		
	}

}
